package com.hnucm.c201901020241.fragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.app.hubert.guide.NewbieGuide;
import com.app.hubert.guide.core.Controller;
import com.app.hubert.guide.listener.OnGuideChangedListener;
import com.app.hubert.guide.listener.OnPageChangedListener;
import com.app.hubert.guide.model.GuidePage;
import com.app.hubert.guide.model.HighLight;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.hnucm.c201901020241.R;
import com.hnucm.c201901020241.WebViewActivity;
import com.hnucm.c201901020241.pojo.DataBean;
import com.hnucm.c201901020241.pojo.News;
import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerAdapter;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.listener.OnPageChangeListener;
import com.youth.banner.transformer.RotateYTransformer;
import com.youth.banner.util.BannerUtils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import java.util.List;
import org.xutils.x;

public class HomeFragment extends Fragment implements OnPageChangeListener{
    Banner banner;
    RecyclerView recyclerView;
    News new_;
    MyAdapter myAdapter;
    Boolean isselect=false;
    private String TAG = HomeFragment.class.getSimpleName();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home, container, false);
    }
//    判断是否是当前的fragment
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser) {
//可见时执行的操作
//            点击了当前的页面

            Log.i("main1","是我");
//            只有isselect是true才代表当前页面是这个
            isselect=true;
        }else{
            Log.i("main1","不是我");
            isselect=false;
//不可见时执行的操作
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {

        //设置轮播图
        banner =getActivity().findViewById(R.id.banner);
        ImageAdapter adapter = new ImageAdapter(DataBean.getTestData());
        banner.setAdapter(adapter)//设置适配器
                .setLoopTime(2000)
                .setCurrentItem(3,false)
                .addBannerLifecycleObserver(this)//添加生命周期观察者
                .setBannerRound(BannerUtils.dp2px(35))//圆角
                .addPageTransformer(new RotateYTransformer())//添加切换效果
                .setIndicator(new CircleIndicator(getContext()));//设置指示器
        // .addOnPageChangeListener(this);//添加切换监听
        //设置recyclerview
        recyclerView=getActivity().findViewById(R.id.recyclerview);
        myAdapter = new MyAdapter();


        x.Ext.init(getActivity().getApplication());
        RequestParams requestParams = new RequestParams("https://www.fastmock.site/mock/2b6bb498237299df2fe3cef9d4479b19/design/infor1");

        x.http().get(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.i("MainActivity","result"+result);
                Gson gson=new Gson();
                new_=gson.fromJson(result,News.class);
                recyclerView.setAdapter(myAdapter);
                recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.i("MainActivity","ex"+ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });


        SharedPreferences sharedPreferences=getActivity().getSharedPreferences("user",getActivity().MODE_MULTI_PROCESS);
        SharedPreferences.Editor editor=sharedPreferences.edit();
        editor.putBoolean("init1",true);
        editor.putBoolean("init2",true);
        editor.putBoolean("init3",false);
        editor.putBoolean("init4",false);
        editor.commit();

        Boolean init=sharedPreferences.getBoolean("init1",false);
        Boolean isfirst=sharedPreferences.getBoolean("isfirst1",false);
        if(init&&!isfirst&&isselect){//是否加载好了，是否是第一次进入，是否是点击了当前位置
            init_NewbieGuide();
            editor.putBoolean("isfirst1",true);
            editor.commit();
        }
//        if(isselect){
////            只有当前页面是这个才能进入以下判断
//            isselect=false;
//            SharedPreferences sharedPreferences=getActivity().getSharedPreferences("user",getActivity().MODE_MULTI_PROCESS);
//            boolean isfirst1 = sharedPreferences.getBoolean("isfirst1", false);
//            if(!isfirst1){
//                init_NewbieGuide();
//                SharedPreferences.Editor editor=sharedPreferences.edit();
//                editor.putBoolean("isfirst1",true);
//                editor.commit();
//            }
//        }


        super.onActivityCreated(savedInstanceState);

    }


    private void init_NewbieGuide() {
        Animation enterAnimation = new AlphaAnimation(0f, 1f);
        enterAnimation.setDuration(600);
        enterAnimation.setFillAfter(true);

        Animation exitAnimation = new AlphaAnimation(1f, 0f);
        exitAnimation.setDuration(600);
        exitAnimation.setFillAfter(true);

        NewbieGuide.with(this)
                .setLabel("home")//设置引导层标示区分不同引导层，必传！否则报错
                .setShowCounts(1)
                .setOnGuideChangedListener(new OnGuideChangedListener() {//引导层显示监听
                    @Override
                    public void onShowed(Controller controller) {
                        Log.e(TAG, "NewbieGuide onShowed: ");
                        //引导层显示
                    }

                    @Override
                    public void onRemoved(Controller controller) {//引导层隐藏监听
                        Log.e(TAG, "NewbieGuide  onRemoved: ");
                        //引导层消失（多页切换不会触发）
                    }
                })
                .setOnPageChangedListener(new OnPageChangedListener() {//引导页切换监听
                    @Override
                    public void onPageChanged(int page) {
                        Log.e(TAG, "NewbieGuide  onPageChanged: " + page);
                        //引导页切换，page为当前页位置，从0开始
                    }
                })
                .alwaysShow(true)//是否每次都显示引导层，默认false，只显示一次
                /**
                 * 添加引导页一
                 */
                .addGuidePage(//添加一页引导页
                        GuidePage.newInstance()//创建一个实例
                                .addHighLight(banner)//添加高亮的view
                                .addHighLight(banner, HighLight.Shape.RECTANGLE)
                                .setLayoutRes(R.layout.homefragment_style)//设置引导页布局
                                .setEnterAnimation(enterAnimation)//进入动画
                                .setExitAnimation(exitAnimation)//退出动画*/
                )

                /**
                 * 添加引导页二
                 */
                .addGuidePage(
                        GuidePage.newInstance()
                                .addHighLight(recyclerView, HighLight.Shape.RECTANGLE, 20)
                                .setLayoutRes(R.layout.homefragment_style2) //引导页布局，点击跳转下一页或者消失引导层的控件id
                                .setEverywhereCancelable(true)//是否点击任意地方跳转下一页或者消失引导层，默认true
//                                        .setBackgroundColor(getResources().getColor(R.color.colorAccent))//设置背景色，建议使用有透明度的颜色
                                .setEnterAnimation(enterAnimation)//进入动画
                                .setExitAnimation(exitAnimation)//退出动画*/
                )
                /**
                 * 展示
                 */
                .show();//显示引导层(至少需要一页引导页才能显示)
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }


    /**
     * 自定义布局，下面是常见的图片样式，更多实现可以看demo，可以自己随意发挥
     */
    public class ImageAdapter extends BannerAdapter<DataBean, ImageAdapter.BannerViewHolder> {

        public ImageAdapter(List<DataBean> mDatas) {
            //设置数据，也可以调用banner提供的方法,或者自己在adapter中实现
            super(mDatas);
        }

        //创建ViewHolder，可以用viewType这个字段来区分不同的ViewHolder
        @Override
        public BannerViewHolder onCreateHolder(ViewGroup parent, int viewType) {
            ImageView imageView = new ImageView(parent.getContext());
            //注意，必须设置为match_parent，这个是viewpager2强制要求的
            imageView.setLayoutParams(new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            return new BannerViewHolder(imageView);
        }

        @Override
        public void onBindView(BannerViewHolder holder, DataBean data, final int position, int size) {
            //holder.imageView.setImageResource(data.imageRes);
            Glide.with(holder.imageView.getContext()).load((String)data.imageUrl).into(holder.imageView);
            holder.itemView.setOnClickListener(
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //点击事件
                            Toast.makeText(v.getContext(),"点击了"+position,Toast.LENGTH_SHORT).show();
                        }
                    }
            );
        }

        class BannerViewHolder extends RecyclerView.ViewHolder {
            ImageView imageView;

            public BannerViewHolder(@NonNull ImageView view) {
                super(view);
                this.imageView = view;
            }
        }
    }
    public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

        @NonNull
        @Override
        public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_news, parent, false);
            MyViewHolder myViewHolder = new MyViewHolder(view);
            return myViewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
            holder.titleTv.setText(new_.news.get(position).title);
            holder.informationTv.setText(new_.news.get(position).information);
            holder.other1Tv.setText(new_.news.get(position).other1);
            holder.other2Tv.setText(new_.news.get(position).other2);
            Glide.with(getActivity()).load(new_.news.get(position).img).into(holder.imageView);
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent=new Intent(getActivity(), WebViewActivity.class);
                    intent.putExtra("url",new_.news.get(position).url);
                    startActivity(intent);
                }
            });
        }

        @Override
        public int getItemCount() {
            return new_.news.size();
        }
    }


    public class MyViewHolder extends RecyclerView.ViewHolder {
        TextView titleTv,informationTv,other1Tv,other2Tv;
        ImageView imageView;
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            titleTv = itemView.findViewById(R.id.textView5);
            informationTv = itemView.findViewById(R.id.textView6);
            other1Tv = itemView.findViewById(R.id.textView7);
            other2Tv = itemView.findViewById(R.id.textView8);
            imageView = itemView.findViewById(R.id.imageView5);
        }
    }
}
